<?php  
class LoginModel extends Model{
	public $table='user';
	/**
	 * 登录
	 * @return [type] [description]
	 */
	public function login(){
		// p($_POST);exit;
		if (trim($_POST['username'])=='') {
			$this->error='用户名不能为空';return false;
		}
		if (trim($_POST['password'])=='') {
			$this->error='密码不能为空';return false;
		}
		$username=Q('username');
		//查找当前登录用户
		$user=$this->join("__user_role__ ur JOIN __user__ u ON ur.uid=u.uid JOIN __role__ r ON r.rid=ur.rid")->where("username='$username'")->find();

		if (!$user) {
			$this->error='该用户不存在';return false;
		}

		if ($user['status']==0) {

			$this->error='该账户被锁定';return false;
		}

		if ($user['password']!=md5($_POST['password'].$user['token'])) {

			$data['uid']=$user['uid'];

			$data['errornum']=$user['errornum']+1;//密码错误次数+1

			if($data['errornum']==4)$data['status']=0;//错误4次时账户被锁定

			$data['errortime']=time();//更新上次错误时间为当前时间

			$this->save($data);

			$this->error=($data['errornum']==4)?'账户被锁定，请联系客服解决':'还有'.(4-$data['errornum']).'次机会';

			return false;
		}
		/**
		 * 30分钟自动清零错误次数
		 */
		if (time()-$user['errortime']>1800) {

			$data['uid']=$user['uid'];

			$data['errornum']=0;

			$this->save($data);
		}

		$_SESSION['user']['uid']=$user['uid'];

		$_SESSION['user']['rid']=$user['rid'];

		$_SESSION['user']['role_name']=$user['role_name'];

		$_SESSION['user']['username']=$user['username'];

		return true;
	}
	/**
	 * 用户注册
	 * @return [type] [description]
	 */
	public function reg(){
		$username=Q('username');

		if (trim($username)=='') {

			$this->error="用户名不能为空";return false;
			
		}
		if (trim($_POST['password'])=='') {

			$this->error="密码不能为空";return false;
			
		}
		if (trim($_POST['repassword'])=='') {

			$this->error="密码不能为空";return false;
			
		}
		if ($_POST['password']!=$_POST['repassword']) {

			$this->error='两次密码不一致';return false;
		}
		if (strtoupper($_POST['code'])!=$_SESSION['code']) {

			$this->error="验证码错误";return false;
			
		}
		//查找当前登录用户
		$user=$this->where("username='$username'")->find();

		if ($user) {

			$this->error='该用户已存在';return false;
		}
		
		$token=md5(mt_rand(0,1000).time());//产生令牌

		
		$_POST['ip']=$_SERVER["REMOTE_ADDR"];

		$_POST['token']=$token;

		$_POST['addtime']=time();

		$_POST['password']=md5($_POST['password'].$token);
		// p($_POST);exit;
		if($uid=$this->add($_POST)){

			$userRole['uid']=$uid;

			$userRole['rid']=2;

			if(M('user_role')->add($userRole)){
				return true;
			}
		}
		return false;
	}
}
